<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="设备编号" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出厂计划id" prop="outFactoryPlanId">
        <el-input
          v-model="queryParams.outFactoryPlanId"
          placeholder="请输入出厂计划id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品型号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否被申请" prop="isApply">
        <el-select  clearable="" v-model="queryParams.isApply"  filterable  placeholder="请选择是否被使用" >
          <el-option v-for="item in isApply_list" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否被使用" prop="isUsed">
        <el-select  clearable="" v-model="queryParams.isUsed"  filterable  placeholder="请选择是否被使用" >
          <el-option v-for="item in isUsed_list" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="importdeviceNo"
        >Excel批量导入设备编号</el-button>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:product-device-no-pool:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['produce:product-device-no-pool:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['produce:product-device-no-pool:removed']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['produce:product-device-no-pool:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ProductDeviceNoPoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="设备编号" align="center" prop="deviceNo" width="220"/>
      <el-table-column label="出厂计划id" align="center" prop="outFactoryPlanId" />
      <el-table-column label="产品型号" align="center" prop="productCode" />
      <el-table-column label="是否被申请" align="center" prop="isApply">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isApply === 0" type="success" >未申请</el-tag>
          <el-tag v-if="scope.row.isApply === 1" type="warning" >已申请</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否被使用" align="center" prop="isUsed">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isUsed === 0" type="success" >未使用</el-tag>
          <el-tag v-if="scope.row.isUsed === 1" type="warning" >已使用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.isApply === 1 && scope.row.isUsed === 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReset(scope.row)"
          >重置</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['produce:product-device-no-pool:edit']"
          >修改</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['produce:product-device-no-pool:removed']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品设备编号池对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceNo">
          <el-input v-model="form.deviceNo" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="出厂计划id" prop="outFactoryPlanId">
          <el-input v-model="form.outFactoryPlanId" placeholder="请输入出厂计划id" />
        </el-form-item>
        <el-form-item label="产品型号" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="是否被申请" prop="isApply">
          <el-input v-model="form.isApply" placeholder="请输入是否被申请" />
        </el-form-item>
        <el-form-item label="是否被使用" prop="isUsed">
          <el-input v-model="form.isUsed" placeholder="请输入是否被使用" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入设备编号" v-loading="importLoading" element-loading-text="请上传excel表格" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :visible.sync="importDialogOpen" :close-on-click-modal="false" @close="cancelUploadExcel" width="800px" append-to-body>
      <el-form label-width="150px">
      <el-row>
          <el-col :span="24">
            <el-form-item label="excel模板：" >
              <ExportExcel :list="exportList" :tHeader="oHeader" :tValue="oValue" filename="导入模板下载">excel导出</ExportExcel>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="请上传excel文件：" >
              <!-- <input type="file"  @change="handUploadExcel"  /> -->
              <el-upload
                action="/"
                :on-change="handUploadExcel"
                :auto-upload="false"
                :show-file-list="false"
                accept=".xls, .xlsx"
              >
              <el-button
                type="success"
                plain
                icon="el-icon-upload"
                size="mini"
                v-hasPermi="['produce:product-sn-info:removed']"
                >请上传excel文件</el-button>
              </el-upload>
              <div style="float: left;">{{ this.excelFileData ? this.excelFileData.name : '' }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUploadExcel" >取 消</el-button>
        <el-button type="primary" @click="submit" >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductDeviceNoPool, getProductDeviceNoPool, removedProductDeviceNoPool, addProductDeviceNoPool, updateProductDeviceNoPool, batchInsertDevicePool } from "@/api/produce/product-device-no-pool";
import ExportExcel from '../../../components/ExcelUtils/Export2Excel.vue'
import * as XLSX from 'xlsx'
export default {
  name: "Product-device-no-pool",
  components: {
    ExportExcel
  },
  data() {
    return {
      // 是否被使用list
      isUsed_list: [{value:0,label:"未使用"},{value:1,label:"已使用"}],
      // 是否被申请list
      isApply_list:  [{value:0,label:"未申请"},{value:1,label:"已申请"}],
      // excel文件数据
      excelFileData:[],
      // 弹出框加载
      importLoading:false,
      // 导出数据集合
      exportList: [],
      // 导出样例的抬头和数据
      oHeader: ['设备编号','生产计划id','产品型号'],
      oValue:['0c1ed4d401a8133976241008','1','HB-CE832-F2'], 
      // 导入Excel弹窗
      importDialogOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品设备编号池表格数据
      ProductDeviceNoPoolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceNo: null,
        outFactoryPlanId: null,
        productCode: null,
        isApply: null,
        isUsed: null,
        removed: null,
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceNo: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 重置 */
    handleReset(row){
      let params = {
        deviceNo:row.deviceNo,
        id:row.id,
        isApply:0,
        isUsed:row.isUsed,
        outFactoryPlanId:row.outFactoryPlanId,
        productCode:row.productCode
      }
      updateProductDeviceNoPool(params).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });

    },
    /** 点击取消提交 */
    cancelUploadExcel(){
      this.importDialogOpen = false
    },
    /** 点击确认-提交表单 */
    submit(){
      if(this.excelFileData){
        const fileReader = new FileReader(this.excelFileData);
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            let workbook = XLSX.read(data, {
              type: "binary",
            });

            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
            // 循环 ws 取得其中的数据 
            // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
            // 没有一样的代码 没有一样的需求

            if(ws.length>0){
              

                var temporary = [];
                for (let i = 0; i < ws.length; i++) {
                  if(ws[i].设备编号 && ws[i].生产计划id){
                    let temp = {
                      deviceNo:ws[i].设备编号,
                      outFactoryPlanId:ws[i].生产计划id,
                      productCode:ws[i].产品型号
                    }
                    temporary.push(temp)
                  }
                }
                if(temporary.length === 0){
                  this.$message.warning("未读取符合“产品规范+生产计划id”规范的数据，请检查excel")
                  return
                }
                this.$notify({
                  title: '提示',
                  message: '批量注册中,请稍后…',
                  offset: 700,
                  duration: 0
                });
                // const formData = new FormData()
                // formData.append("productDeviceNoPools", temporary)
                batchInsertDevicePool(temporary)
                .then((res) => {
                  if(res.code === 200){
                    this.$message.success("注册成功,详情："+res.msg)
                    this.importDialogOpen = false
                    this.getList()
                  }else{
                    this.$message.warning("注册失败，原因："+res.msg)
                  }
                  this.$notify.closeAll();//去掉交互框
                })
                .catch((err) => {
                  this.$message.error('通过excel批量新增设备编号-接口返回：'+err.message)
                })
             
            }else{
                this.$message({
                  type: "info",
                  message: "获取的列表为空，请检查表格是否有数据!",
                });
            }

          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(this.excelFileData.raw);
      }else{
        this.$message({
          type: 'warning',
          message: '请先上传Excel'
        })
      }
    },
    /** 点击-上传Excel文件 */
    handUploadExcel(file,fileList){
      // 校验文件
      if (!file) {
        this.$confirm("读取excel文件数据失败，请尝试重新上传文件！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      }else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      // 准备读取文件数据
      this.excelFileData = file
      this.$message.success("上传成功")
    },
    /** 点击-Excel批量导入设备编号 */
    importdeviceNo(){
      this.excelFileData = null
      this.importDialogOpen = true
    },
    /** 查询产品设备编号池列表 */
    getList() {
      this.loading = true;
      listProductDeviceNoPool(this.queryParams).then(response => {
        this.ProductDeviceNoPoolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceNo: null,
        outFactoryPlanId: null,
        productCode: null,
        isApply: null,
        isUsed: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        removed: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品设备编号池";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProductDeviceNoPool(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品设备编号池";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProductDeviceNoPool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductDeviceNoPool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品设备编号池编号为"' + ids + '"的数据项？').then(function() {
          // 修改为逻辑删除
        return removedProductDeviceNoPool(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('produce/product-device-no-pool/export', {
        ...this.queryParams
      }, `product-device-no-pool_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
